<template>
    <div class="params-box">
      <!--面包屑导航-->
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item><a href="/">商品管理</a></el-breadcrumb-item>
        <el-breadcrumb-item>商品参数</el-breadcrumb-item>
      </el-breadcrumb>
      <!--内容&操作区-->
      <el-card class="box-card">
        <!--操作提示-->
        <el-alert
          title="注意：只允许为三级分类设置相关参数！"
          :closable="false"
          class="m-b"
          show-icon
          type="warning">
        </el-alert>
        <!--级别选择器-->
        <el-row class="m-b">
          <el-col>
            <span class="cate-label">请选择商品分类：</span>
            <el-cascader
              v-model="cateSelectKeys"
              :options="cateList"
              :props="cateListProps"
              clearable
              @change="cateSelectChange"></el-cascader>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-tabs v-model="activeName" @tab-click="handleCateClick">
              <el-tab-pane label="动态参数" name="many">
                <el-button type="primary" :disabled="isCanOp" @click="addPropsParams()">添加参数</el-button>
                <el-table
                  :data="manyData"
                  border
                  style="width: 100%">
                  <el-table-column
                    label="#"
                    type="index"
                    width="50">
                  </el-table-column>
                  <el-table-column
                    type="expand">
                      <template v-slot="scope">
                        <div class="tag-box">
                          <el-tag
                            v-for="(item, index) in scope.row.attr_vals"
                            :key="index"
                            closable
                            @close="deleteTag(index,scope.row)"
                          >{{item}}</el-tag>
                          <!--文本框与按钮切换-->
                          <el-input
                            class="input-new-tag"
                            v-if="scope.row.inputVisible"
                            v-model="scope.row.inputValue"
                            ref="saveTagInput"
                            size="small"
                            @keyup.enter.native="handleInputConfirm(scope.row)"
                            @blur="handleInputConfirm(scope.row)"
                          >
                          </el-input>
                          <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ 添加新参数</el-button>
                        </div>
                      </template>
                  </el-table-column>
                  <el-table-column
                    prop="attr_name"
                    label="参数名称"
                    >
                  </el-table-column>
                  <el-table-column
                    label="操作"
                    width="300px"
                    >
                    <template v-slot="scope">
                      <!--编辑属性信息-->
                      <el-button type="primary" icon="el-icon-edit" size="medium"
                                 @click="editProps(scope.row.attr_id)"></el-button>
                      <!--删除属性信息-->
                      <el-button type="danger" icon="el-icon-delete" size="medium"
                                 @click="deletePropParams(scope.row.attr_id)"></el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
              <el-tab-pane label="静态属性" name="only">
                <el-button type="primary"  :disabled="isCanOp" @click="addPropsParams()">添加属性</el-button>
                <el-table
                  :data="onlyData"
                  border
                  style="width: 100%">
                  <el-table-column
                    label="#"
                    type="index"
                    width="50">
                  </el-table-column>
                  <el-table-column
                    type="expand"
                  >
                    <template v-slot="scope">
                      <div class="tag-box">
                        <el-tag
                          v-for="(item, index) in scope.row.attr_vals"
                          :key="index"
                          closable
                          @close="deleteTag(index,scope.row)"
                        >{{item}}</el-tag>
                        <!--文本框与按钮切换-->
                        <el-input
                          class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)"
                        >
                        </el-input>
                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ 添加新属性</el-button>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="attr_name"
                    label="属性名称"
                    >
                  </el-table-column>
                  <el-table-column
                    label="操作"
                    width="300px"
                    >
                    <template v-slot="scope">
                      <!--编辑属性信息-->
                      <el-button type="primary" icon="el-icon-edit" size="medium"
                                 @click="editProps(scope.row.attr_id)"></el-button>
                      <!--删除属性信息-->
                      <el-button type="danger" icon="el-icon-delete" size="medium"
                                 @click="deletePropParams(scope.row.attr_id)"></el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>
      </el-card>
      <!--修改分类属性对话框-->
      <el-dialog
        :title="dialogName"
        :visible.sync="editPropsdialogVisible"
        :close-on-click-modal="false"
        width="30%"
        @close="editPropsdialogClose">
        <div class="editProps-box">
          <el-form :model="propsInfo" :rules="propsInfoRules" ref="propsInfoRef" label-width="70px"
                   class="demo-ruleForm">
            <el-form-item label="属性名" prop="attr_name">
              <el-input v-model="propsInfo.attr_name"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editPropsdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateParamsProps">确 定</el-button>
        </span>
      </el-dialog>

      <!--添加商品分类参数&属性对话框-->
      <el-dialog
        :title="dialogName"
        :visible.sync="addParamsPropsdialogVisible"
        width="30%"
        :close-on-click-modal="false"
        @close="editPropsdialogClose">
        <div class="editProps-box">
          <el-form :model="propsInfo" :rules="propsInfoRules" ref="propsInfoRef" label-width="90px"
                   class="demo-ruleForm">
            <el-form-item :label="labelName" prop="attr_name">
              <el-input v-model="propsInfo.attr_name"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addParamsPropsdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmAddPropsParams">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
export default {
  name: 'params',
  data(){
    return {
      // 所有分类的数据
      cateList:[],
      // 已选择分类的id数组
      cateSelectKeys:[],
      // 请求参数
      queryInfo: {
        type: 3,
      },
      // 级联选择器渲染规则及交互
      cateListProps:{
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        checkStrictly: true,
        expandTrigger: 'hover'
      },
      // tabs默认显示项
      activeName: 'many',
      // 动态参数数据
      manyData: [],
      // 静态数据数据
      onlyData: [],
      // 修改分类属性对话框显示控制
      editPropsdialogVisible: false,
      // 静态属性信息
      propsInfo:{
        id: 0,
        attrId: 0,
        attr_name: '',
        attr_sel:'',
      },
      // 参数id
      paramsId: 0,
      // 属性id
      propsId: 0,
      // 修改参数&属性名称
      dialogName:'',
      // 分类属性规则
      propsInfoRules: {
        attr_name: [
          {required: true, message: '请输入属性名称', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
        ],
      },
      // 添加动态参数或属性对话框显示控制
      addParamsPropsdialogVisible: false,
      // 添加动态参数或属性对话框label名称
      labelName:'',
      // 按钮与文本框显示
      inputVisible: false,
      // 文本框输入的内容
      inputValue:'',
    }
  },
  created() {
    this.getCateList()
  },
  methods:{
    // 获取分类数据
    async getCateList() {
      const {data: res} = await this.$http.get(`categories`,{params: this.queryInfo})
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    },
    // 过滤选择三级分类
    cateSelectChange(val){
      console.log(`选择的是${val}`)
      if(val.length !== 3) {
        // 没有选择三级分类 重置绑定渲染的表格数据及级联选择选择的数组数据
        this.cateSelectKeys = []
        this.manyData=[]
        this.onlyData=[]
        return this.$message.error('请选择三级的分类进行操作！')
      }else{
        console.log('选择的分类id是', this.cateSelectKeys)
        this.getParameters()
      }
    },
    handleCateClick(tab, event) {
      console.log(tab, event);
      console.log('点击是', this.activeName);
      // 选择了三级分类进行相关参数请求
      if(!this.isCanOp){
        this.getParameters()
      }
    },
    // 添加商品参数或属性
    async addPropsParams(){
      this.addParamsPropsdialogVisible = true
      if(this.activeName === 'many'){
        this.dialogName = '添加商品参数'
        this.labelName = '参数名称'
      }else{
        this.dialogName = '添加商品属性'
        this.labelName = '属性名称'
      }
    },
    // 确认添加商品参数或属性
    async confirmAddPropsParams(){
      const {data: res} = await this.$http.post(`categories/${this.cateId}/attributes`, {attr_name:this.propsInfo.attr_name,attr_sel:this.activeName})
      if(res.meta.status !== 201) return this.$message.error(res.meta.msg)
      // 提交成功 重置表单
      this.$refs.propsInfoRef.resetFields()
      // 提交成功 对话框隐藏
      this.addParamsPropsdialogVisible = false
      // 提交成功 提示信息
      this.$message.success(res.meta.msg)
      // 提交成功 重新获取列表数据
      this.getParameters()
    },
    // 调用获取相关分类参数 动态参数 many 静态属性 only
    async getParameters(){
      console.log('选择的分类id是', this.cateId)
      const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {params: {sel: this.activeName}})
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // this.$message.success(res.meta.msg)
      res.data.forEach((item)=>{
        // 返回参数值，如果不为空，在分割，否则返回空数组
        item.attr_vals = item.attr_vals?item.attr_vals.split(','):[]
        // 控制对应的文本框是否显示
        item.inputVisible = false
        // 控制对应的文本框值为空
        item.inputValue = ''
      })
      console.log('格式化参数值', res.data)
      if(this.activeName === 'many'){
        this.manyData = res.data
      }else{
        this.onlyData = res.data
      }
    },
    // 编辑分类属性
    editProps(id){
      console.log('编辑分类属性', id)
      this.propsId = id
      this.getPropsById()
      this.editPropsdialogVisible = true
    },
    // 编辑提交参数
    async updateParamsProps(){
      const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.propsId}`, {attr_name: this.propsInfo.attr_name,attr_sel: this.activeName})
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 提交操作成功 重置表单
      this.editPropsdialogVisible = false
      // 提交操作成功 重置表单
      this.$refs.propsInfoRef.resetFields()
      // 提交操作成功 重新获取参数列表数据
      this.getParameters()
      // 提交操作成功 提示成功
      this.$message.success(res.meta.msg)
    },
    // 根据id查询参数&属性信息
    async getPropsById(){
      const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes/${this.propsId}`, {params: {attr_sel: this.activeName,}})
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // this.$message.success(res.meta.msg)
      if(this.activeName === 'many'){
        this.propsInfo = res.data
        this.dialogName = '修改商品参数'
      }else{
        this.propsInfo = res.data
        this.dialogName = '修改商品属性'
      }
    },
    // 删除参数&属性
    async deletePropParams(id){
      // 删除弹窗提示 确定 confirm 取消 cancel
      const deleteOp = await this.$confirm('此操作将永久删除该属性, 是否继续?', '操作提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err)=>{
        return err
      })
      console.log('确认框提示', deleteOp)
      if(deleteOp !=='confirm'){
        return this.$message.info('已经取消删除')
      }
      const {data: res} = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 删除操作成功 重新获取列表数据
      this.getParameters()
      // 删除操作成功 提示信息
      this.$message.success(res.meta.msg)
    },
    // 监控编辑对话框关闭事件
    editPropsdialogClose(){
      this.$refs.propsInfoRef.resetFields()
    },
    // 参数或属性标签删除事件
    async deleteTag(i,attrVals){
      // 删除弹窗提示 确定 confirm 取消 cancel
      const deleteOp = await this.$confirm('此操作将永久删除该参数, 是否继续?', '操作提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err)=>{
        return err
      })
      if(deleteOp !=='confirm'){
        return this.$message.info('已经取消删除')
      }
      // 删除对应下标的数组元素
      attrVals.attr_vals.splice(i,1)
      const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${attrVals.attr_id}`, {attr_name: attrVals.attr_name,attr_sel: this.activeName, attr_vals: attrVals.attr_vals.join(',')})
      if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 提成成功信息
      this.$message.success(res.meta.msg)
    },
    // 文本框失去焦点回车键触发
    async handleInputConfirm(attrVals){
      // 过滤空格
      const inputValue = attrVals.inputValue.trim()
      if(inputValue.length !== 0 ){
        // 文本框有值，放入数组
        attrVals.attr_vals.push(attrVals.inputValue)
        const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${attrVals.attr_id}`, {attr_name: attrVals.attr_name,attr_sel: this.activeName, attr_vals: attrVals.attr_vals.join(',')})
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        // 隐藏文本框
        attrVals.inputVisible = false
        // 重置文本框
        attrVals.inputValue = ''
        // 提成成功信息
        this.$message.success(res.meta.msg)
      }
      // 放入数组后，隐藏文本框
      attrVals.inputVisible = false
      // 放入数组后，重置文本框
      attrVals.inputValue = ''
    },
    // 点击按钮显示文本框
    showInput(attrVals){
      attrVals.inputVisible = true
      // 只有当页面重新渲染之后，在回调函数中执行dom相关操作，否则找不到该dom元素
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
  },
  computed:{
    // 判断按钮是否被禁用
    isCanOp(){
      if(this.cateSelectKeys.length !== 3){
        return true
      }
      return false
    },
    // 获取分类id
    cateId(){
      if(this.cateSelectKeys.length === 3){
        return this.cateSelectKeys[2]
      }
      return null
    }
  }
}
</script>

<style lang="scss">
.el-cascader{
  width: 30%;
}
::v-deep .el-cascader-panel{
  height: 300px !important;
}
.cate-label{
  font-size: 14px;
}
.m-b{
  margin-bottom: 15px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.tag-box{
  display: flex;
  align-items: center;
}
</style>
